<template>
    <div class="chat-panel">
        <div v-if="!isDataLoaded" class="loading-container">
            <el-icon class="is-loading" style="font-size: 24px;">
                <loading />
            </el-icon>
        </div>
        <div v-else class="chat-body">
            <div class="messages" ref="messageList">
                <div v-if="messages.length === 0" class="empty-chat">
                    <i class="el-icon-chat-dot-round"></i>
                    <p>群组聊天开始了</p>
                </div>
                
                <div v-for="(message, index) in messages" :key="index" class="message-row" :class="{
                    'outgoing': isSentMessage(message),
                    'incoming': !isSentMessage(message)
                }">
                    <div class="avatar-container" v-if="!isSentMessage(message)">
                        <el-avatar :size="36" :src="getSenderAvatar(message.from)" @click="showUserProfile(message.from)"></el-avatar>
                    </div>
                    <div class="message">
                        <div class="message-time" @click="showUserProfile(message.from)">{{ getSenderName(message.from) }}</div>
                        <div class="message-content">
                            <p>{{ message.content }}</p>
                        </div>
                        <div class="message-status" v-if="isSentMessage(message)">
                            <i class="el-icon-check"></i>
                        </div>
                    </div>
                    <div class="avatar-container" v-if="isSentMessage(message)">
                        <el-avatar :size="36" :src="store.state.me.userPicture" @click="showUserProfile(store.state.me.userEmail)"></el-avatar>
                    </div>
                </div>
            </div>

            <div class="message-composer">
                <div class="composer-input">
                    <el-input
                        v-model="newMessage"
                        type="textarea"
                        :rows="3"
                        resize="none"
                        placeholder="输入消息..."
                        @keyup.enter.native="sendMessage"
                    ></el-input>
                </div>
                
                <div class="composer-actions">
                    <el-button
                        type="primary"
                        :disabled="!newMessage.trim()"
                        @click="sendMessage"
                        class="send-btn"
                    >
                        <i class="el-icon-position"></i>
                        <span>发送</span>
                    </el-button>
                </div>
            </div>
        </div>
        
        <!-- 用户信息弹窗 -->
        <el-dialog
          title="用户信息"
          :visible.sync="userProfileVisible"
          width="500px"
          custom-class="user-profile-dialog"
          :before-close="handleCloseUserProfile">
          <div v-if="selectedUser" class="user-profile-content">
            <div class="user-profile-header">
              <el-avatar :size="80" :src="selectedUser.userPicture || defaultAvatar"></el-avatar>
              <div class="user-profile-info">
                <h3>{{ selectedUser.userName }}</h3>
                <p>{{ selectedUser.userEmail }}</p>
              </div>
            </div>
            <div class="user-profile-details">
              <div class="detail-item">
                <span class="detail-label">专业：</span>
                <span class="detail-value">{{ getDeptName(selectedUser.dept_id) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">性别：</span>
                <span class="detail-value">{{  selectedUser.userSex || '未设置'}}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">年龄：</span>
                <span class="detail-value">{{ selectedUser.userAge || '未设置' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">国籍：</span>
                <span class="detail-value">{{ selectedUser.userFrom || '未设置' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">个人简介：</span>
                <p class="detail-value">{{ selectedUser.userSelf || '暂无简介' }}</p>
              </div>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="userProfileVisible = false">关闭</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
import {addlittleGroupMessage, getGroupMessage, getUserByGroup, getUserInfo} from "@/api/api";
import store from "@/store";
import loading from "@/components/Loading.vue";

export default {
    name: "Chat",
    components: {
        loading
    },
    computed: {
        store() {
            return store;
        },
        userMap() {
            const map = {};
            this.GroupUser.forEach(user => {
                map[user.userEmail] = user;
            });
            map[this.store.state.me.userEmail] = {
                userEmail: this.store.state.me.userEmail,
                userPicture: this.store.state.me.userPicture
            };
            return map;
        }
    },
    data() {
        return {
            GroupUser: [],
            group: null,
            active: null,
            newMessage: '',
            messages: [],
            loading: false,
            isDataLoaded: false,
            userProfileVisible: false,
            selectedUser: null,
            defaultAvatar: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
        };
    },
    methods: {
        getSenderAvatar(email) {
            const sender = this.userMap[email];
            return sender?.userPicture || this.getDefaultAvatar(email);
        },

        getDefaultAvatar(email) {
            return `https://ui-avatars.com/api/?name=${encodeURIComponent(email)}&background=random`;
        },

        isSentMessage(message) {
            return message.from === this.store.state.me.userEmail;
        },

        getSenderName(email) {
            if (email === this.store.state.me.userEmail) {
                return '我';
            }
            const sender = this.userMap[email];
            return sender ? sender.userEmail : email;
        },

        async loadData() {
                this.isDataLoaded = false;
                await this.InitMessages(this.group.groupId);
                this.isDataLoaded = true;
        },

        async sendMessage() {
            if (this.newMessage.trim() !== '') {
                this.loading = true;
                
                // 保存消息内容并立即清空输入框
                const messageContent = this.newMessage;
                this.newMessage = '';
                
                this.messages.push({
                    to: this.group.groupId,
                    from: this.store.state.me.userEmail,
                    content: messageContent
                });

                try {
                    if (this.GroupUser.length === 0) {
                        await this.getUserByGroup(this.group.groupId);
                    }

                    this.store.state.websocket.send(JSON.stringify({
                        type: 'Groupmessage',
                        message: messageContent,
                        to: this.GroupUser,
                        from: this.store.state.me.userEmail,
                        groupId: this.group.groupId
                    }));

                    const response = await addlittleGroupMessage({
                        to: this.group.groupId,
                        content: messageContent,
                    });

                    if (response.data.message === "成功") {
                        // 移除成功提示，保持界面干净
                        this.scrollToBottom();
                    } else {
                        this.$message.error("发送信息失败");
                        this.messages.pop();
                    }
                } catch (error) {
                    console.error('发送消息失败:', error);
                    this.$message.error("发送信息失败");
                    this.messages.pop();
                } finally {
                    this.loading = false;
                    this.scrollToBottom();
                }
            }
        },

        async InitMessages(groupId) {
            await this.getUserByGroup(groupId);
            try {
                const response = await getGroupMessage({
                    params: {
                        to: groupId,
                    },
                });
                this.messages = response.data.data;
                this.scrollToBottom();
            } catch (error) {
                console.error('Error fetching messages:', error);
                throw error;
            }
        },

        scrollToBottom() {
            this.$nextTick(() => {
                const messageList = this.$refs.messageList;
                if (messageList) {
                    messageList.scrollTop = messageList.scrollHeight;
                }
            });
        },

        async getUserByGroup(groupId) {
            try {
                const response = await getUserByGroup({
                    groupId: groupId,
                });
                this.GroupUser = response.data.data;
            } catch (error) {
                console.error('Error fetching group users:', error);
                throw error;
            }
        },


        async initPage() {
            // 确保count参数存在
            if (!this.$route.query.count) {
                // 可以在这里添加重定向或错误处理
                console.error('缺少count参数');
                return;
            }

            this.group = this.$route.query.count;
            await this.loadData(); // 假设loadData是异步的
        },
        
        // 获取部门名称
        getDeptName(deptId) {
            if (!deptId) return '未设置';
            const dept = this.$store.state.deptList.find(dept => dept.dept_id === deptId);
            return dept ? dept.dept_name : '未知部门';
        },
        
        // 显示用户个人主页
        async showUserProfile(userEmail) {
            if (!userEmail) return;
            
            this.loading = true;
            try {
                const response = await getUserInfo(userEmail);
                if (response.data.message === "成功") {
                    this.selectedUser = response.data.data;
                    this.userProfileVisible = true;
                } else {
                    this.$message.error("获取用户信息失败");
                }
            } catch (error) {
                console.error("获取用户信息出错:", error);
                this.$message.error("获取用户信息出错");
            } finally {
                this.loading = false;
            }
        },
        
        // 关闭用户个人主页
        handleCloseUserProfile() {
            this.userProfileVisible = false;
            this.selectedUser = null;
        }
    },
    async  mounted() {
        await this.$nextTick();
        await this.initPage();

        // 监听 WebSocket 消息
        this.store.state.websocket.onmessage = (event) => {
            const message = JSON.parse(event.data);
            this.messages.push({
                to: message.to,
                from: message.from,
                content: message.content
            });
        };
    },

    watch: {
        '$route.query.count': {
            immediate: true,
            handler(newCount) {
                if (newCount) {
                    this.group = newCount;
                    this.initPage();
                }
            }
        },
        messages: {
            deep: true,
            handler() {
                this.scrollToBottom();
            }
        }
    }
}
</script>


<style scoped>
.chat-panel {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    background-color: white;
    border-radius: 8px;
    overflow: hidden;
}

.loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    flex-direction: column;
    gap: 10px;
}

.chat-body {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: #f8f9fa;
    position: relative;
    overflow: hidden;
    padding-bottom: 30px;
}

.messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    scroll-behavior: smooth;
}

.empty-chat {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #5f6368;
}

.empty-chat i {
    font-size: 48px;
    margin-bottom: 16px;
    color: #dadce0;
}

.message-row {
    display: flex;
    margin-bottom: 16px;
    align-items: flex-end;
}

.incoming {
    justify-content: flex-start;
}

.outgoing {
    justify-content: flex-end;
}

.avatar-container {
    margin: 0 8px;
}

.message {
    display: flex;
    flex-direction: column;
    max-width: 65%;
}

.incoming .message {
    align-items: flex-start;
}

.outgoing .message {
    align-items: flex-end;
}

.message-time {
    font-size: 11px;
    color: #5f6368;
    margin-bottom: 4px;
}

.message-content {
    padding: 12px 16px;
    border-radius: 18px;
    position: relative;
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.15);
}

.incoming .message-content {
    background-color: white;
    border-top-left-radius: 4px;
    color: #202124;
}

.outgoing .message-content {
    background-color: #1a73e8;
    border-top-right-radius: 4px;
    color: white;
}

.message-content p {
    margin: 0;
    line-height: 1.4;
    font-size: 15px;
    white-space: pre-wrap;
    word-break: break-word;
}

.message-status {
    font-size: 12px;
    color: #34a853;
    margin-top: 4px;
}

.message-composer {
    padding: 16px;
    padding-bottom: 30px;
    background-color: white;
    border-top: 1px solid #dadce0;
    position: relative;
    bottom: 16px;
    margin-bottom: -16px;
}

.composer-input {
    margin-bottom: 12px;
    margin-top: 16px;
}

.composer-input >>> .el-textarea__inner {
    border-radius: 8px;
    border: 1px solid #dadce0;
    padding: 12px;
    font-size: 15px;
    transition: all 0.2s;
}

.composer-input >>> .el-textarea__inner:focus {
    border-color: #1a73e8;
    box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.2);
}

.composer-actions {
    display: flex;
    justify-content: flex-end;
}

.send-btn {
    border-radius: 24px;
    background-color: #1a73e8;
    border: none;
    padding: 8px 16px;
    font-weight: 500;
    transition: all 0.2s;
}

.send-btn:hover:not(:disabled) {
    background-color: #1765c9;
    transform: translateY(-1px);
}

.send-btn:disabled {
    background-color: #dadce0;
    color: #9aa0a6;
}

.send-btn i {
    margin-right: 6px;
}

/* 用户个人主页弹窗样式 */
.user-profile-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.user-profile-dialog :deep(.el-dialog__header) {
  background-color: #f0f2f7;
  padding: 16px 20px;
  border-bottom: 1px solid #e0e5ef;
}

.user-profile-dialog :deep(.el-dialog__title) {
  font-weight: 600;
  color: #333;
}

.user-profile-dialog :deep(.el-dialog__body) {
  padding: 24px;
}

.user-profile-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.user-profile-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.user-profile-info h3 {
  margin: 0 0 4px 0;
  font-size: 18px;
  color: #333;
}

.user-profile-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.user-profile-details {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-item {
  display: flex;
}

.detail-label {
  width: 80px;
  font-weight: 500;
  color: #666;
}

.detail-value {
  flex: 1;
  color: #333;
}

/* 添加鼠标悬停效果 */
.avatar-container .el-avatar, .message-time {
  cursor: pointer;
  transition: all 0.3s;
}

.avatar-container .el-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.message-time:hover {
  color: #1a73e8;
  text-decoration: underline;
}
</style>
